﻿using System;
using System.Collections.Generic;
using System.Data;
using System.Web.UI.WebControls;
using CDOP.Model;
using CDOP.Utility;

namespace CDOP
{
    public partial class SearchPatient : System.Web.UI.Page
    {
        protected int? CurrentPageNo = 1;
        List<MasterTable> _patients;

        protected void Page_Load(object sender, EventArgs e)
        {
            if (!IsPostBack)
            {
                if (Session["LoggedUser"] == null)
                    Response.Redirect("Login.aspx");
                BindData();
                Session["CurrentLoadedPatients"] = _patients;
            }

        }

        public void BindData()
        {
            dvPagination.Visible = true;
            int totalRecordCount;
            var db = new MasterTable();
            var isFirstName = Session["IsFirstName"] != null ? (bool)Session["IsFirstName"] : false;
            var isLastName = Session["IsLastName"] != null ? (bool)Session["IsLastName"] : false;
            var isNhsNumber = Session["IsNhsNumber"] != null ? (bool)Session["IsNhsNumber"] : false;
            var isCdopRef = Session["IsCdopRef"] != null ? (bool)Session["IsCdopRef"] : false;

            if (isFirstName)
                _patients = db.SearchByFirstName(CurrentPageNo, grdPatients.PageSize, out totalRecordCount, txtFirstName.Text);
            else if (isLastName)
                _patients = db.SearchByLastName(CurrentPageNo, grdPatients.PageSize, out totalRecordCount, txtLastName.Text);
            else if (isNhsNumber)
                _patients = db.SearchByNhsRef(CurrentPageNo, grdPatients.PageSize, out totalRecordCount, txtNhsNumber.Text);
            else if (isCdopRef)
                _patients = db.SearchByCdopRef(CurrentPageNo, grdPatients.PageSize, out totalRecordCount, txtCdopRef.Text);
            else
                _patients = db.GetAllPatients(CurrentPageNo, grdPatients.PageSize, out totalRecordCount);
            grdPatients.DataSource = _patients;
            grdPatients.DataBind();
            if ((((UserDetails)Session["LoggedUser"]).UserType.Type.ToLower() != "admin"))
                grdPatients.Columns[14].Visible = false;
            //manage pagination
            var totalPageCount = CalculateTotalPages(totalRecordCount);
            lbltotalPageNo.Text = totalPageCount.ToString();
            lblCurrentPage.Text = CurrentPageNo.ToString();
            if (CurrentPageNo == 1)
            {
                btnPrevious.Enabled = false;
                var currentPageNumber = Int32.Parse(lbltotalPageNo.Text);
                btnNext.Enabled = totalRecordCount > grdPatients.PageSize && currentPageNumber > 0 && currentPageNumber <= totalPageCount;
            }
            else
            {
                btnPrevious.Enabled = true;
                var currentPageNumber = Int32.Parse(lblCurrentPage.Text);
                btnNext.Enabled = currentPageNumber != totalPageCount;
            }
        }

        #region Pagination

        private int CalculateTotalPages(double totalRows)
        {
            int totalPages = grdPatients.PageSize == totalRows ? 2 : (int)Math.Ceiling(totalRows / grdPatients.PageSize);
            return totalPages;
        }

        protected void ChangePage(object sender, CommandEventArgs e)
        {
            switch (e.CommandName)
            {
                case "Previous":
                    CurrentPageNo = Int32.Parse(lblCurrentPage.Text) - 1;
                    break;

                case "Next":
                    CurrentPageNo = Int32.Parse(lblCurrentPage.Text) + 1;
                    break;
            }
            BindData();
        }

        #endregion

        protected void BtnFirstNameClick(object sender, EventArgs e)
        {
            Session["IsFirstName"] = true;
            Session["IsLastName"] = false;
            Session["IsNhsNumber"] = false;
            Session["IsCdopRef"] = false;
            BindData();
        }

        protected void BtnLastNameClick(object sender, EventArgs e)
        {
            Session["IsFirstName"] = false;
            Session["IsLastName"] = true;
            Session["IsNhsNumber"] = false;
            Session["IsCdopRef"] = false;
            BindData();
        }

        protected void BtnNhsNumberClick(object sender, EventArgs e)
        {
            Session["IsFirstName"] = false;
            Session["IsLastName"] = false;
            Session["IsNhsNumber"] = true;
            Session["IsCdopRef"] = false;
            BindData();
        }

        protected void BtnCdopRefClick(object sender, EventArgs e)
        {
            Session["IsFirstName"] = false;
            Session["IsLastName"] = false;
            Session["IsNhsNumber"] = false;
            Session["IsCdopRef"] = true;
            BindData();
        }

        protected void BtnShowAllClick(object sender, EventArgs e)
        {
            Session["IsFirstName"] = false;
            Session["IsLastName"] = false;
            Session["IsNhsNumber"] = false;
            Session["IsCdopRef"] = false;
            BindData();
        }

        protected void GrdPatientsRowDeleting(object sender, GridViewDeleteEventArgs e)
        {
            var cdopRef = Convert.ToInt32(e.Values["CDOP_Ref"]);
            var status = new MasterTable().DeleteMasterRecord(cdopRef);
            BindData();
        }

        protected void BtnExportClick(object sender, EventArgs e)
        {
            var patients = Session["CurrentLoadedPatients"] as List<MasterTable>;
            ExportToExcel(patients);
        }

        public void ExportToExcel(List<MasterTable> data)
        {
            var table = Helper.ConvertTo(data, "SearchPatient");
            const string attachment = "attachment; filename=ExportedData.xls";
            Response.ClearContent();
            Response.AddHeader("content-disposition", attachment);
            Response.ContentType = "application/vnd.ms-excel";
            var tab = string.Empty;
            foreach (DataColumn dc in table.Columns)
            {
                Response.Write(tab + dc.ColumnName);
                tab = "\t";
            }
            Response.Write("\n");
            foreach (DataRow dr in table.Rows)
            {
                tab = string.Empty;
                int i;
                for (i = 0; i < table.Columns.Count; i++)
                {
                    Response.Write(tab + dr[i]);
                    tab = "\t";
                }
                Response.Write("\n");
            }
            Response.End();
        }
    }
}